package com.ywb.edugui.utils;

import com.alibaba.druid.pool.DruidDataSource;
import com.alibaba.druid.pool.DruidDataSourceFactory;

import javax.sql.DataSource;
import java.io.IOException;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Properties;

public class JDBCUtils {
    //得到配置文件对象
    private static Properties properties = new Properties();
    private static DruidDataSource dataSource = null;

    static{
        try {
            //加载配置文件（输入流）
            InputStream in = JDBCUtils.class.getClassLoader().getResourceAsStream("datasource.properties");
            //通过load()方法将输入流加载到配置对象中
            properties.load(in);
            dataSource = (DruidDataSource) DruidDataSourceFactory.createDataSource(properties);

        } catch (IOException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static Connection getConnection() throws SQLException {

        return dataSource.getConnection();
    }
    public static void close(Connection conn, PreparedStatement ps, ResultSet rs){
        try{
            if(conn != null)
                conn.close();
            if(ps != null)
                ps.close();
            if(rs != null)
                rs.close();
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
    }
}
